package com.example.managemyself.config;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 应用配置管理类
 * 统一管理所有配置信息，包括数据库连接、API配置、邮箱配置等
 */
public class AppConfig {
    private static final String TAG = "AppConfig";
    private static final String PREF_NAME = "app_config";
    
    // 配置文件名
    private static final String CONFIG_FILE = "app_config.properties";
    
    // 单例实例
    private static AppConfig instance;
    private Properties properties;
    private Context context;
    
    // 数据库配置键
    public static final String DB_HOST = "db.host";
    public static final String DB_PORT = "db.port";
    public static final String DB_NAME = "db.name";
    public static final String DB_USERNAME = "db.username";
    public static final String DB_PASSWORD = "db.password";
    public static final String DB_USE_SSL = "db.use_ssl";
    
    // API配置键
    public static final String API_BASE_URL = "api.base_url";
    
    // 天气API配置键
    public static final String WEATHER_API_URL = "weather.api_url";
    public static final String WEATHER_API_ID = "weather.api_id";
    public static final String WEATHER_API_KEY = "weather.api_key";
    
    // 天行API配置键
    public static final String TIANAPI_URL = "tianapi.url";
    public static final String TIANAPI_KEY = "tianapi.key";
    
    // DeepSeek API配置键
    public static final String DEEPSEEK_API_URL = "deepseek.api_url";
    public static final String DEEPSEEK_API_KEY = "deepseek.api_key";
    public static final String DEEPSEEK_MODEL = "deepseek.model";
    
    // 邮箱配置键
    public static final String EMAIL_SMTP_HOST = "email.smtp.host";
    public static final String EMAIL_SMTP_PORT = "email.smtp.port";
    public static final String EMAIL_USERNAME = "email.username";
    public static final String EMAIL_PASSWORD = "email.password";
    public static final String EMAIL_USE_TLS = "email.use_tls";
    
    // 应用配置键
    public static final String APP_VERSION = "app.version";
    public static final String APP_DEBUG_MODE = "app.debug_mode";
    public static final String APP_LOG_LEVEL = "app.log_level";
    
    // 默认用户配置键
    public static final String DEFAULT_ADMIN_USERNAME = "default.admin.username";
    public static final String DEFAULT_ADMIN_PASSWORD = "default.admin.password";
    public static final String DEFAULT_ADMIN_EMAIL = "default.admin.email";
    public static final String DEFAULT_USER_USERNAME = "default.user.username";
    public static final String DEFAULT_USER_PASSWORD = "default.user.password";
    public static final String DEFAULT_USER_EMAIL = "default.user.email";
    
    private AppConfig() {
        properties = new Properties();
        loadDefaultConfig();
    }
    
    /**
     * 获取单例实例
     */
    public static synchronized AppConfig getInstance() {
        if (instance == null) {
            instance = new AppConfig();
        }
        return instance;
    }
    
    /**
     * 初始化配置管理器
     */
    public void init(Context context) {
        this.context = context.getApplicationContext();
        loadConfigFromAssets();
        loadConfigFromPreferences();
    }
    
    /**
     * 加载默认配置
     */
    private void loadDefaultConfig() {
        // 数据库默认配置
        properties.setProperty(DB_HOST, "10.163.78.16");
        properties.setProperty(DB_PORT, "3306");
        properties.setProperty(DB_NAME, "managemyself");
        properties.setProperty(DB_USERNAME, "root");
        properties.setProperty(DB_PASSWORD, "Lth20030329");
        properties.setProperty(DB_USE_SSL, "false");
        
        // API默认配置
        properties.setProperty(API_BASE_URL, "http://10.163.78.16:8080/api");
        properties.setProperty(WEATHER_API_KEY, "your_weather_api_key");
        properties.setProperty(TIANAPI_KEY, "your_tianapi_key");
        
        // 邮箱默认配置
        properties.setProperty(EMAIL_SMTP_HOST, "smtp.gmail.com");
        properties.setProperty(EMAIL_SMTP_PORT, "587");
        properties.setProperty(EMAIL_USERNAME, "your_email@gmail.com");
        properties.setProperty(EMAIL_PASSWORD, "your_email_password");
        properties.setProperty(EMAIL_USE_TLS, "true");
        
        // 应用默认配置
        properties.setProperty(APP_VERSION, "1.0.0");
        properties.setProperty(APP_DEBUG_MODE, "true");
        properties.setProperty(APP_LOG_LEVEL, "DEBUG");
        
        // 默认用户配置
        properties.setProperty(DEFAULT_ADMIN_USERNAME, "admin");
        properties.setProperty(DEFAULT_ADMIN_PASSWORD, "admin123");
        properties.setProperty(DEFAULT_ADMIN_EMAIL, "admin@managemyself.com");
        properties.setProperty(DEFAULT_USER_USERNAME, "user");
        properties.setProperty(DEFAULT_USER_PASSWORD, "user123");
        properties.setProperty(DEFAULT_USER_EMAIL, "user@managemyself.com");
    }
    
    /**
     * 从assets文件夹加载配置文件
     */
    private void loadConfigFromAssets() {
        if (context == null) return;
        
        try {
            InputStream inputStream = context.getAssets().open(CONFIG_FILE);
            Properties fileProperties = new Properties();
            fileProperties.load(inputStream);
            
            // 合并配置，文件配置覆盖默认配置
            for (String key : fileProperties.stringPropertyNames()) {
                properties.setProperty(key, fileProperties.getProperty(key));
            }
            
            inputStream.close();
            Log.i(TAG, "配置文件加载成功");
        } catch (IOException e) {
            Log.w(TAG, "配置文件不存在或加载失败，使用默认配置: " + e.getMessage());
        }
    }
    
    /**
     * 从SharedPreferences加载配置
     */
    private void loadConfigFromPreferences() {
        if (context == null) return;
        
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        
        // 加载所有保存的配置
        for (String key : prefs.getAll().keySet()) {
            String value = prefs.getString(key, null);
            if (value != null) {
                properties.setProperty(key, value);
            }
        }
    }
    
    /**
     * 获取字符串配置
     */
    public String getString(String key) {
        return properties.getProperty(key);
    }
    
    /**
     * 获取字符串配置（带默认值）
     */
    public String getString(String key, String defaultValue) {
        return properties.getProperty(key, defaultValue);
    }
    
    /**
     * 获取整数配置
     */
    public int getInt(String key, int defaultValue) {
        try {
            String value = properties.getProperty(key);
            return value != null ? Integer.parseInt(value) : defaultValue;
        } catch (NumberFormatException e) {
            Log.w(TAG, "配置值格式错误: " + key + " = " + properties.getProperty(key));
            return defaultValue;
        }
    }
    
    /**
     * 获取布尔配置
     */
    public boolean getBoolean(String key, boolean defaultValue) {
        String value = properties.getProperty(key);
        return value != null ? Boolean.parseBoolean(value) : defaultValue;
    }
    
    /**
     * 设置配置值
     */
    public void setString(String key, String value) {
        properties.setProperty(key, value);
        saveToPreferences(key, value);
    }
    
    /**
     * 设置整数配置
     */
    public void setInt(String key, int value) {
        setString(key, String.valueOf(value));
    }
    
    /**
     * 设置布尔配置
     */
    public void setBoolean(String key, boolean value) {
        setString(key, String.valueOf(value));
    }
    
    /**
     * 保存配置到SharedPreferences
     */
    private void saveToPreferences(String key, String value) {
        if (context == null) return;
        
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putString(key, value).apply();
    }
    
    /**
     * 获取数据库连接URL
     */
    public String getDatabaseUrl() {
        String host = getString(DB_HOST);
        String port = getString(DB_PORT);
        String dbName = getString(DB_NAME);
        boolean useSSL = getBoolean(DB_USE_SSL, false);
        
        return String.format("jdbc:mysql://%s:%s/%s?useSSL=%s&serverTimezone=UTC&allowPublicKeyRetrieval=true",
                host, port, dbName, useSSL);
    }
    
    /**
     * 获取数据库用户名
     */
    public String getDatabaseUsername() {
        return getString(DB_USERNAME);
    }
    
    /**
     * 获取数据库密码
     */
    public String getDatabasePassword() {
        return getString(DB_PASSWORD);
    }
    
    /**
     * 获取API基础URL
     */
    public String getApiBaseUrl() {
        return getString(API_BASE_URL);
    }
    
    /**
     * 获取天行API密钥
     */
    public String getTianApiKey() {
        return getString(TIANAPI_KEY);
    }
    
    /**
     * 获取天行API URL
     */
    public String getTianApiUrl() {
        return getString(TIANAPI_URL, "https://apis.tianapi.com/lunar/index");
    }
    
    /**
     * 获取天气API URL
     */
    public String getWeatherApiUrl() {
        return getString(WEATHER_API_URL, "https://cn.apihz.cn/api/tianqi/tqyb.php");
    }
    
    /**
     * 获取天气API ID
     */
    public String getWeatherApiId() {
        return getString(WEATHER_API_ID, "88888888");
    }
    
    /**
     * 获取天气API密钥
     */
    public String getWeatherApiKey() {
        return getString(WEATHER_API_KEY, "88888888");
    }
    
    /**
     * 获取DeepSeek API URL
     */
    public String getDeepSeekApiUrl() {
        return getString(DEEPSEEK_API_URL, "https://api.deepseek.com/v1/chat/completions");
    }
    
    /**
     * 获取DeepSeek API密钥
     */
    public String getDeepSeekApiKey() {
        // 先从SharedPreferences获取，如果没有则使用配置文件中的默认值
        String key = getString(DEEPSEEK_API_KEY);
        if (key == null || key.isEmpty() || key.equals("your_deepseek_api_key")) {
            // 返回内置的API密钥
            return "sk-aaa6320f47554c5eb46185826e7f9cd7";
        }
        return key;
    }
    
    /**
     * 获取DeepSeek模型名称
     */
    public String getDeepSeekModel() {
        return getString(DEEPSEEK_MODEL, "deepseek-chat");
    }
    
    /**
     * 是否为调试模式
     */
    public boolean isDebugMode() {
        return getBoolean(APP_DEBUG_MODE, false);
    }
    
    /**
     * 获取默认管理员用户名
     */
    public String getDefaultAdminUsername() {
        return getString(DEFAULT_ADMIN_USERNAME);
    }
    
    /**
     * 获取默认管理员密码
     */
    public String getDefaultAdminPassword() {
        return getString(DEFAULT_ADMIN_PASSWORD);
    }
    
    /**
     * 获取默认管理员邮箱
     */
    public String getDefaultAdminEmail() {
        return getString(DEFAULT_ADMIN_EMAIL);
    }
    
    /**
     * 获取默认用户用户名
     */
    public String getDefaultUserUsername() {
        return getString(DEFAULT_USER_USERNAME);
    }
    
    /**
     * 获取默认用户密码
     */
    public String getDefaultUserPassword() {
        return getString(DEFAULT_USER_PASSWORD);
    }
    
    /**
     * 获取默认用户邮箱
     */
    public String getDefaultUserEmail() {
        return getString(DEFAULT_USER_EMAIL);
    }
    
    /**
     * 重置所有配置为默认值
     */
    public void resetToDefaults() {
        if (context != null) {
            SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            prefs.edit().clear().apply();
        }
        
        properties.clear();
        loadDefaultConfig();
        
        Log.i(TAG, "配置已重置为默认值");
    }
    
    /**
     * 打印所有配置（调试用）
     */
    public void printAllConfigs() {
        if (!isDebugMode()) return;
        
        Log.d(TAG, "=== 应用配置信息 ===");
        for (String key : properties.stringPropertyNames()) {
            String value = properties.getProperty(key);
            // 隐藏敏感信息
            if (key.contains("password") || key.contains("key")) {
                value = "***";
            }
            Log.d(TAG, key + " = " + value);
        }
        Log.d(TAG, "==================");
    }
}
